<?php

namespace app\api\model;

use think\Cache;
use app\common\library\wechat\WxUser;
use app\common\exception\BaseException;
use app\common\model\User as UserModel;
use app\api\model\dealer\Referee as RefereeModel;
use app\api\model\dealer\Setting as DealerSettingModel;
use think\Db;

/**
 * 用户模型类
 * Class User
 * @package app\api\model
 */
class User extends UserModel
{
    private $token;

    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'open_id',
        'is_delete',
        'wxapp_id',
        'create_time',
        'update_time'
    ];

    /**
     * 获取用户信息
     * @param $token
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function getUser($token)
    {
        $openId = Cache::get($token)['openid'];
        return self::detail(['open_id' => $openId], ['address', 'addressDefault', 'grade', 'team']);
    }

    /**
     * 用户登录
     * @param array $post
     * @return string
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login($post)
    {
        // 微信登录 获取session_key
        $session = $this->wxlogin($post['code']);
        // 自动注册用户
        $refereeId = isset($post['referee_id']) ? $post['referee_id'] : null;
        $userInfo = json_decode(htmlspecialchars_decode($post['user_info']), true);
        $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $str = $protocol . $_SERVER['HTTP_HOST'] . '/uploads';
        $user = Db::name('user')->where('open_id', $session['openid'])->where('wxapp_id', self::$wxapp_id)->where('is_delete', 0)->find();
//        if ($user && $user['nickName'] != '微信用户') {
//            $userInfo['nickName'] = $user['nickName'];
//        } else {
//            $userInfo['nickName'] = '';
//        }
//        if ($user && strpos($user['avatarUrl'], $str) !== false) {
//            $userInfo['avatarUrl'] = $user['avatarUrl'];
//        } else {
//            $userInfo['avatarUrl'] = '';
//        }
        $user_id = $this->register($session['openid'], $userInfo, $refereeId);
        // 生成token (session3rd)
        $this->token = $this->token($session['openid']);
        // 记录缓存, 7天
        Cache::set($this->token, $session, 86400 * 7);
        return $user_id;
    }

    /**
     * 获取token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * 微信登录
     * @param $code
     * @return array|mixed
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function wxlogin($code)
    {
        // 获取当前小程序信息
        $wxConfig = Wxapp::getWxappCache();
        // 验证appid和appsecret是否填写
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            throw new BaseException(['msg' => '请到 [后台-小程序设置] 填写appid 和 appsecret']);
        }
        // 微信登录 (获取session_key)
        $WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);
        if (!$session = $WxUser->sessionKey($code)) {
            throw new BaseException(['msg' => $WxUser->getError()]);
        }
        return $session;
    }

    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($openid)
    {
        $wxapp_id = self::$wxapp_id;
        // 生成一个不会重复的随机字符串
        $guid = \getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'token_salt';
        return md5("{$wxapp_id}_{$timeStamp}_{$openid}_{$guid}_{$salt}");
    }

    /**
     * 自动注册用户
     * @param $open_id
     * @param $data
     * @param int $refereeId
     * @return mixed
     * @throws \Exception
     * @throws \think\exception\DbException
     */
    private function register($open_id, $data, $refereeId = null)
    {
        // 查询用户是否已存在
        $user = self::detail(['open_id' => $open_id]);
        if ($user) {
            return $user['user_id'];
        }
        $model = $user ?: $this;
        $this->startTrans();
        try {
            // 保存/更新用户记录
            if (!$model->allowField(true)->save(array_merge($data, [
                'open_id' => $open_id,
                'wxapp_id' => self::$wxapp_id
            ]))) {
                throw new BaseException(['msg' => '用户注册失败']);
            }
            // 记录推荐人关系
            if (!$user && $refereeId > 0) {
                RefereeModel::createRelation($model['user_id'], $refereeId);
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new BaseException(['msg' => $e->getMessage()]);
        }
        return $model['user_id'];
    }

    /**
     * 个人中心菜单列表
     * @return array
     */
    public function getMenus($user = [])
    {
        if (isset($user['grade_id']) && $user['grade_id'] > 0) {
            $menus = [
                'my_company' => [
                    'name' => '我的公司管理',
                    'url' => 'pages/company/edit/index',
                    'icon' => 'tubiao_kuaizhuangpailie'
                ],
                'shanghuiSetting' => [
                    'name' => '商会基础设置',
                    'url' => 'pages/shanghui/edit/index',
                    'icon' => 'favorite'
                ],
                'shanghui_examine' => [
                    'name' => '入会申请审核',
                    'url' => 'pages/shanghui/examine/index',
                    'icon' => 'favorite'
                ],
                'shanghui_banner' => [
                    'name' => '首页banner管理',
                    'url' => 'pages/shanghui/banner/index',
                    'icon' => 'favorite'
                ],
                'leader' => [
                    'name' => '领导团队管理',
                    'url' => 'pages/leader/manager/index',
                    'icon' => 'favorite'
                ],
                'aboutus' => [
                    'name' => '关于我们管理',
                    'url' => 'pages/introduce/manager/index',
                    'icon' => 'favorite'
                ],
                'my_news' => [
                    'name' => '新闻管理',
                    'url' => 'pages/user/news/index',
                    'icon' => 'z-new'
                ],
                'my_activity' => [
                    'name' => '活动管理',
                    'url' => 'pages/user/activity/index',
                    'icon' => 'lingquan'
                ],
                'activity_examine' => [
                    'name' => '活动审核',
                    'url' => 'pages/user/activity/approve/index',
                    'icon' => 'lingquan'
                ],
                'my_photos' => [
                    'name' => '服务队相册管理',
                    'url' => 'pages/team/photo/index',
                    'icon' => 'sy-yh'
                ],
               
            ];
            if (!isset($user['examine_role']) || $user['examine_role'] <= 0) {
                unset($menus['activity_examine']);
            }
            // 没有服务队
            if (isset($user['team_id']) && $user['team_id'] == 0) {
                unset($menus['my_photos']);
            }
        }else{
            $menus = [
                'my_company' => [
                    'name' => '我的公司管理',
                    'url' => 'pages/company/edit/index',
                    'icon' => 'tubiao_kuaizhuangpailie'
                ]
            ];
        }
       
        // 
//        if (isset($user['grade_id']) && $user['grade_id'] <= 0) {
//            unset($menus['my_news']);
//            unset($menus['my_activity']);
//        }
//        if ($user['grade_id'] != 10007) {
//            unset($menus['my_photos']);
//        }
        // 判断分销功能是否开启
//        if (DealerSettingModel::isOpen()) {
//            $menus['dealer']['name'] = DealerSettingModel::getDealerTitle();
//        } else {
//            unset($menus['dealer']);
//        }
        return $menus;
    }

}
